import { isString, isNumber, isObject } from "./pubFunction"

export type DB<T = 0> = {
    DbName: string,
    Where: Record<string, any>,
    Id: string,
    Data: T extends 0 ? Record<string, any> : Array<Record<string, any>>,
    Page?: number,
    PageSize?: number,
    Field?: Record<string, any>,
    AddFields?: Record<string, any>,
    NeedCount?: Boolean,
    Sort?: Record<string, any>
}

export async function list(option: Omit<DB, 'Id' | 'Data' | 'AddFields'>) {
    try {
        const {
            DbName = '', Where = {}, Page, PageSize, Field, Sort, NeedCount
        } = option
        if (!isString(DbName)) throw new Error("DbName类型错误")
        if (!isObject(Where)) throw new Error("Where类型错误")
        const db = uniCloud.database();
        const DB = db.collection(DbName).where(Where)

        if (Page) {
            if (!isNumber(Page)) throw new Error("Page类型错误")
            if (Page < 1) throw new Error("Page需大于1")
            const page = PageSize ? (Page - 1) * PageSize : Page
            DB.skip(page)
        }
        if (PageSize) {
            if (!isNumber(PageSize)) throw new Error("PageSize类型错误")
            if (PageSize < 1) throw new Error("PageSize需大于1")
            DB.limit(PageSize)
        }
        if (Field) {
            if (!isObject(Field)) throw new Error("Field类型错误")
            DB.field(Field)
        }
        if (Sort) {
            if (!isObject(Sort)) throw new Error("Sort类型错误")
            Object.keys(Sort).forEach(item => {
                DB.orderBy(`${item}`, `${Sort[item]}`)
            })
        }
        const { data } = await DB.get()
        let count = data.length
        if (NeedCount) {
            const { total } = await db.collection(DbName).where(Where).count()
            count = total
        }
        return {
            errCode: 0,
            data,
            count,
            errMsg: data.length > 0 ? '查询成功' : '暂无数据'
        }
    } catch (err: any) {
        return {
            errCode: err.code || err.name || 400,
            errMsg: err.message || "未知错误"
        }
    }
}

export async function add(option: Pick<DB<1>, 'DbName' | 'Data'>) {
    try {
        const { DbName = '', Data } = option
        if (!isString(DbName)) throw new Error("DbName类型错误")
        const db = uniCloud.database();
        const { inserted } = await db.collection(DbName).add(Data)
        return {
            errCode: inserted === Data.length ? 0 : -1,
            errMsg: inserted === Data.length ? '新增成功' : inserted === 0 ? '添加失败' :
                `数据添加不完整，${inserted}/${Data.length}条数据新增成功`
        }
    } catch (err: any) {
        return {
            errCode: err.code || err.name || 400,
            errMsg: err.message || "未知错误"
        }
    }
}
export async function edit(option: Pick<DB, 'DbName' | 'Data' | 'Where'>) {
    try {
        const { DbName = '', Where = {}, Data } = option
        if (!isString(DbName)) throw new Error("DbName类型错误")
        if (!isObject(Where)) throw new Error("Where类型错误")
        if (!isObject(Data)) throw new Error("Data类型错误")
        const db = uniCloud.database();
        const { updated } = await db.collection(DbName).where(Where).update(Data)
        return {
            errCode: updated > 0 ? 0 : -1,
            errMsg: updated > 0 ? '更新成功' : '更新失败'
        }
    } catch (err: any) {
        return {
            errCode: err.code || err.name || 400,
            errMsg: err.message || "未知错误"
        }
    }
}

export async function set(option: Pick<DB, 'DbName' | 'Data' | 'Id'>) {
    try {
        const { DbName = '', Id = '', Data } = option
        if (!isString(DbName)) throw new Error("DbName类型错误")
        if (!isString(Id)) throw new Error("Id类型错误")
        if (!isObject(Data)) throw new Error("Data类型错误")
        const db = uniCloud.database();
        const { updated } = await db.collection(DbName).doc(Id).set(Data)
        return {
            errCode: updated > 0 ? 0 : -1,
            errMsg: updated > 0 ? '更新成功' : '更新失败'
        }
    } catch (err: any) {
        return {
            errCode: err.code || err.name || 400,
            errMsg: err.message || "未知错误"
        }
    }
}

export async function remove(option: Pick<DB, 'DbName' | 'Where'>) {
    try {
        const { DbName = '', Where = {} } = option
        if (!isString(DbName)) throw new Error("DbName类型错误")
        if (!isObject(Where)) throw new Error("Where类型错误")
        const db = uniCloud.database();
        const { deleted } = await db.collection(DbName).where(Where).remove()
        return {
            errCode: deleted > 0 ? 0 : -1,
            errMsg: deleted > 0 ? '删除成功' : '删除失败'
        }
    } catch (err: any) {
        return {
            errCode: err.code || err.name || 400,
            errMsg: err.message || "未知错误"
        }
    }

}